//
//  NewPlayerManager.m
//  CommonAppSHL
//
//  Created by mac on 2021/6/7.
//

#import "NewPlayerManager.h"
// 音频播放
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "BBVoiceRecordController.h"

@interface NewPlayerManager ()
@property (nonatomic, assign) NSInteger status;
@property(nonatomic,strong)AVPlayerItem *songItem;
@end

@implementation NewPlayerManager
#pragma mark - 单例
+ (instancetype)manager{
    static NewPlayerManager *manage;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manage = [NewPlayerManager new];
    });
    return manage;
}

- (void)playNetMusic:(NSString *)url_str{
    NSURL *url = [NSURL URLWithString:url_str];
    self.songItem = [AVPlayerItem playerItemWithURL:url];// 2.创建AVPlayerItem
    [self.songItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    self.player = [AVPlayer playerWithPlayerItem:self.songItem];// 3.创建AVPlayer
    // 监听AVPlayer播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.songItem];

    [CCToast showMessage:@"加载中..."];
    [self.player play];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
     
    if ([keyPath isEqualToString:@"status"]) {
//        [MBProgressHUD hideAllHUDsForView:appDelegate.window animated:YES];
        switch (self.player.status) {
            case AVPlayerStatusUnknown:
                NSLog(@"KVO：未知状态，此时不能播放");
                break;
            case AVPlayerStatusReadyToPlay:
                self.status = 1;
                NSLog(@"KVO：准备完毕，可以播放");
                [self.player play];
                break;
            case AVPlayerStatusFailed:
                NSLog(@"KVO：加载失败，网络或者服务器出现问题");
                break;
            default:
                break;
        }
    }
}
- (void)playerPause{
    if (self.player) {
        [self.player pause];
    }
}
- (void)playbackFinished:(NSNotification *)notice {
    NSLog(@"播放完成");
    [CCToast showMessage:@"播放完成"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DidPlaybackFinished" object:nil];
    [self.songItem removeObserver:self forKeyPath:@"status"];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
